package jinyilw.swing.visuals.comp;

import jinyilw.common.Operator;

import javax.swing.Icon;
import java.util.ArrayList;

public class SwitchIconComp extends ActIconComp
{
	private static final long serialVersionUID = -337559647319096021L;
	private Icon openIcon, openOverIcon;
	private Icon closeIcon, closeOverIcon;
	private boolean opened = false;
	private volatile ArrayList<Operator<Object>> turnOnOperators;
	private volatile ArrayList<Operator<Object>> turnOffOperators;

	public SwitchIconComp()
	{
		addClickOperator(createSwitchOperator());
	}

	public SwitchIconComp(Icon oic, Icon ooic, Icon cic, Icon coic)
	{
		this();
		setSwitchIcon(oic, ooic, cic, coic);
	}

	public void setSwitchIcon(Icon oic, Icon ooic, Icon cic, Icon coic)
	{
		openIcon = oic;
		openOverIcon = ooic;
		closeIcon = cic;
		closeOverIcon = coic;
		if (opened)
			setActionIcon(openIcon, openOverIcon);
		else
			setActionIcon(closeIcon, closeOverIcon);
	}

	public void turnOn()
	{
		if (opened)
			return;
		opened = true;
		setActionIcon(openIcon, openOverIcon);
	}

	public void turnOff()
	{
		if (!opened)
			return;
		opened = false;
		setActionIcon(closeIcon, closeOverIcon);
	}

	public boolean isOpened()
	{
		return opened;
	}

	public void addTurnOnOperators(Operator<Object> operator)
	{
		if (turnOnOperators == null)
			createTurnOnOperators();
		turnOnOperators.add(operator);
	}

	public void addTurnOffOperators(Operator<Object> operator)
	{
		if (turnOffOperators == null)
			createTurnOffOperators();
		turnOffOperators.add(operator);
	}

	private synchronized void createTurnOnOperators()
	{
		if (turnOnOperators == null)
			turnOnOperators = new ArrayList<>();
	}

	private synchronized void createTurnOffOperators()
	{
		if (turnOffOperators == null)
			turnOffOperators = new ArrayList<>();
	}

	protected Operator<Object> createSwitchOperator()
	{
		return e -> {
			if (opened)
			{
				turnOff();
				if (turnOffOperators != null)
					for (Operator<Object> operator : turnOffOperators)
						operator.operate(e);
			} else
			{
				turnOn();
				if (turnOnOperators != null)
					for (Operator<Object> operator : turnOnOperators)
						operator.operate(e);
			}
		};
	}
}
